<template>
	<view class="community-container">
		<view class="header">
			<view class="title">社区交流</view>
			<button class="post-btn" @tap="createPost">发布</button>
		</view>
		
		<view class="tag-list">
			<view 
				class="tag-item" 
				v-for="(tag, index) in tags" 
				:key="index"
				:class="{ active: currentTag === index }"
				@tap="switchTag(index)"
			>
				{{ tag.name }}
			</view>
		</view>
		
		<view class="post-list">
			<view class="empty-tip" v-if="filteredPosts.length === 0">
				暂无帖子，成为第一个发帖的人吧
			</view>
			<view class="post-item" v-for="(item, index) in filteredPosts" :key="item.id" @tap="viewDetail(item)">
				<view class="post-header">
					<view class="user-info">
						<!-- 有头像则显示头像，没有则显示文字头像 -->
						<view v-if="item.userAvatar" class="user-avatar">
							<image :src="item.userAvatar" mode="aspectFill" class="avatar-image"></image>
						</view>
						<view v-else class="user-avatar" :style="{ backgroundColor: item.userColor }">
							{{ item.userNickname.substring(0, 1) }}
						</view>
						<view class="user-nickname">{{ item.userNickname }}</view>
						<view class="post-time">{{ formatTime(item.createTime) }}</view>
					</view>
					<view class="post-tag" :style="{ backgroundColor: getTagColor(item.tagId, 0.1), color: getTagColor(item.tagId) }">
						{{ getTagName(item.tagId) }}
					</view>
				</view>
				
				<view class="post-content">
					<view class="post-title">{{ item.title }}</view>
					<view class="post-text">{{ item.content }}</view>
					<view class="post-images" v-if="item.images && item.images.length > 0">
						<image 
							v-for="(img, imgIndex) in item.images" 
							:key="imgIndex" 
							:src="img" 
							mode="aspectFill" 
							class="post-image"
							@tap.stop="previewImage(item.images, imgIndex)"
						></image>
					</view>
				</view>
				
				<view class="post-footer">
					<view class="action-item" @tap.stop="likePost(item)">
						<t-icon :name="item.isLiked ? 'heart-filled' : 'heart'" size="22" :color="item.isLiked ? '#ff6b6b' : '#999999'"></t-icon>
						<text class="count">{{ item.likes }}</text>
					</view>
					<view class="action-item">
						<t-icon name="chat" size="22" color="#999999"></t-icon>
						<text class="count">{{ item.comments.length }}</text>
					</view>
					<view class="action-item">
						<t-icon name="share" size="22" color="#999999"></t-icon>
						<text class="count">分享</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view class="load-more" v-if="filteredPosts.length > 0">
			<text v-if="loading">加载中...</text>
			<text v-else-if="hasMore" @tap="loadMore">点击加载更多</text>
			<text v-else>没有更多了</text>
		</view>
		
		<!-- 悬浮发布按钮 -->
		<view class="float-btn" @tap="createPost">
			<t-icon name="edit" size="24" color="#ffffff"></t-icon>
		</view>
	</view>
	<custom-tabbar></custom-tabbar>
</template>

<script setup>
	import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
	import { getCommunityPosts, likePost as likePostApi } from '@/common/api/community.js'
	import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
	
	// 确保__route__存在
	if (typeof __route__ === 'undefined') {
		try {
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			// @ts-ignore
			global.__route__ = currentPage.route;
		} catch (e) {
			console.error('获取当前页面路径失败:', e);
			// @ts-ignore
			global.__route__ = '/pages/community/index';
		}
	}
	
	// 标签列表
	const tags = [
		{ id: 0, name: '全部', color: '#8cc9a1' },
		{ id: 1, name: '求助', color: '#f0ad4e' },
		{ id: 2, name: '分享', color: '#5bc0de' },
		{ id: 3, name: '讨论', color: '#d9534f' },
		{ id: 4, name: '经验', color: '#9370db' },
		{ id: 5, name: '饮食', color: '#28a745' },
		{ id: 6, name: '运动', color: '#fd7e14' },
		{ id: 7, name: '科普', color: '#17a2b8' }
	]
	
	// 当前选中的标签索引
	const currentTag = ref(0)
	
	// 帖子列表
	const posts = ref([])
	
	// 加载状态
	const loading = ref(false)
	const hasMore = ref(true)
	const page = ref(1)
	const pageSize = 10
	
	// 根据标签筛选帖子
	const filteredPosts = computed(() => {
		if (currentTag.value === 0) {
			return posts.value
		} else {
			return posts.value.filter(post => post.tagId === tags[currentTag.value].id)
		}
	})
	
	// 切换标签
	const switchTag = (index) => {
		currentTag.value = index
	}
	
	// 获取标签名称
	const getTagName = (tagId) => {
		const tag = tags.find(t => t.id === tagId)
		return tag ? tag.name : '未知'
	}
	
	// 获取标签颜色
	const getTagColor = (tagId, alpha = 1) => {
		const tag = tags.find(t => t.id === tagId)
		if (!tag) return '#8cc9a1'
		
		if (alpha === 1) {
			return tag.color
		} else {
			// 将颜色转换为rgba格式
			const color = tag.color
			if (color.startsWith('#')) {
				const r = parseInt(color.slice(1, 3), 16)
				const g = parseInt(color.slice(3, 5), 16)
				const b = parseInt(color.slice(5, 7), 16)
				return `rgba(${r}, ${g}, ${b}, ${alpha})`
			}
			return color
		}
	}
	
	// 格式化时间
	const formatTime = (timestamp) => {
		let date;
		
		// 处理数组格式的日期 [年, 月, 日, 时, 分, 秒]
		if (Array.isArray(timestamp)) {
			date = new Date(timestamp[0], timestamp[1]-1, timestamp[2], timestamp[3], timestamp[4], timestamp[5]);
		} else {
			date = new Date(timestamp);
		}
		
		const now = new Date();
		const diff = now - date;
		
		// 小于1分钟
		if (diff < 60 * 1000) {
			return '刚刚';
		}
		// 小于1小时
		if (diff < 60 * 60 * 1000) {
			return `${Math.floor(diff / (60 * 1000))}分钟前`;
		}
		// 小于24小时
		if (diff < 24 * 60 * 60 * 1000) {
			return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
		}
		// 小于30天
		if (diff < 30 * 24 * 60 * 60 * 1000) {
			return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
		}
		
		// 超过30天显示具体日期
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		const day = date.getDate();
		return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
	}
	
	// 点赞帖子
	const likePost = async (post) => {
		try {
			// 更新本地状态
			const isLike = !post.isLiked
			post.isLiked = isLike
			post.likes = isLike ? post.likes + 1 : Math.max(0, post.likes - 1)
			
			// 调用API保存点赞状态
			const res = await likePostApi(post.id, isLike)
			
			if (res.code === 0) {
				uni.showToast({
					title: isLike ? '点赞成功' : '已取消点赞',
					icon: 'none'
				})
			} else {
				throw new Error(res.message || '操作失败')
			}
		} catch (e) {
			console.error('点赞失败:', e)
			// 恢复原状态
			post.isLiked = !post.isLiked
			post.likes = post.isLiked ? post.likes + 1 : Math.max(0, post.likes - 1)
			
			uni.showToast({
				title: '操作失败，请重试',
				icon: 'none'
			})
		}
	}
	
	// 预览图片
	const previewImage = (images, current) => {
		// 确保images是数组类型
		const imageUrls = Array.isArray(images) ? images : [];
		if (imageUrls.length === 0) return;
		
		uni.previewImage({
			urls: imageUrls,
			current: imageUrls[current] || imageUrls[0]
		});
	}
	
	// 查看帖子详情
	const viewDetail = (post) => {
		uni.navigateTo({
			url: `/pages/community/detail?id=${post.id}`
		})
	}
	
	// 创建帖子
	const createPost = () => {
		try {
			uni.navigateTo({
				url: '/pages/community/post',
				fail: (err) => {
					console.error('导航失败:', err)
					uni.showToast({
						title: '页面跳转失败，请重试',
						icon: 'none'
					})
				}
			})
		} catch (e) {
			console.error('导航异常:', e)
			uni.showToast({
				title: '页面跳转异常，请重试',
				icon: 'none'
			})
		}
	}
	
	// 加载更多
	const loadMore = async () => {
		if (loading.value || !hasMore.value) return;
		
		loading.value = true;
		page.value++;
		
		try {
			const res = await getCommunityPosts({ page: page.value, pageSize });
			if (res.code === 0) {
				// 处理帖子数据
				const postData = res.data.list || [];
				
				// 处理每个帖子的图片数据
				postData.forEach(post => {
					// 将JSON字符串转换为数组
					if (typeof post.images === 'string') {
						try {
							post.images = JSON.parse(post.images);
						} catch (e) {
							post.images = [];
						}
					}
					
					// 确保评论是一个数组
					if (!post.comments) {
						post.comments = [];
					}
					
					// 将liked字段初始化为false，如果没有
					if (post.liked === undefined) {
						post.liked = false;
					}

					// 处理用户头像为空的情况
					if (!post.userAvatar || post.userAvatar === 'null' || post.userAvatar === 'undefined') {
						post.userAvatar = '';
					}
				});
				
				if (postData.length === 0) {
					hasMore.value = false;
				} else {
					posts.value = [...posts.value, ...postData];
					hasMore.value = postData.length >= pageSize && res.data.total > page.value * pageSize;
				}
			} else {
				throw new Error(res.message || '加载失败');
			}
		} catch (e) {
			console.error('加载帖子失败:', e);
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	}
	
	// 加载帖子列表
	const loadPosts = async () => {
		loading.value = true;
		
		try {
			const res = await getCommunityPosts({ page: page.value, pageSize });
			if (res.code === 0) {
				// 处理帖子数据
				const postData = res.data.list || [];
				
				// 处理每个帖子的图片数据
				postData.forEach(post => {
					// 将JSON字符串转换为数组
					if (typeof post.images === 'string') {
						try {
							post.images = JSON.parse(post.images);
						} catch (e) {
							post.images = [];
						}
					}
					
					// 确保评论是一个数组
					if (!post.comments) {
						post.comments = [];
					}
					
					// 将liked字段初始化为false，如果没有
					if (post.liked === undefined) {
						post.liked = false;
					}

					// 处理用户头像为空的情况
					if (!post.userAvatar || post.userAvatar === 'null' || post.userAvatar === 'undefined') {
						post.userAvatar = '';
					}
				});
				
				posts.value = postData;
				hasMore.value = postData.length >= pageSize && res.data.total > page.value * pageSize;
			} else {
				throw new Error(res.message || '加载失败');
			}
		} catch (e) {
			console.error('加载帖子失败:', e);
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	}
	
	// 页面下拉刷新
	onPullDownRefresh(() => {
		page.value = 1
		loadPosts().then(() => {
			uni.stopPullDownRefresh()
		})
	})
	
	// 页面加载时获取帖子列表
	onMounted(() => {
		loadPosts()
	})
</script>

<style lang="scss">
	.community-container {
		padding: 20rpx;
		padding-bottom: 120rpx;
		min-height: 100vh;
		background-color: #f5f7fa;
		
		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;
			
			.title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
			
			.post-btn {
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				line-height: 1.5;
			}
		}
		
		.tag-list {
			display: flex;
			overflow-x: auto;
			margin-bottom: 20rpx;
			white-space: nowrap;
			background-color: #fff;
			border-radius: 12rpx;
			padding: 15rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			
			.tag-item {
				padding: 10rpx 30rpx;
				margin-right: 20rpx;
				font-size: 28rpx;
				color: #666;
				background-color: #f5f5f5;
				border-radius: 30rpx;
				
				&.active {
					background-color: #8cc9a1;
					color: #fff;
				}
				
				&:last-child {
					margin-right: 0;
				}
			}
		}
		
		.post-list {
			.empty-tip {
				color: #999;
				font-size: 28rpx;
				text-align: center;
				background-color: #fff;
				padding: 100rpx 0;
				border-radius: 12rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			}
			
			.post-item {
				background-color: #fff;
				border-radius: 12rpx;
				padding: 20rpx;
				margin-bottom: 20rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
				
				.post-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 15rpx;
					
					.user-info {
						display: flex;
						align-items: center;
						
						.user-avatar {
							width: 60rpx;
							height: 60rpx;
							background-color: #f0f8f3;
							color: #fff;
							font-size: 28rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							border-radius: 50%;
							margin-right: 10rpx;
							overflow: hidden;
							
							.avatar-image {
								width: 100%;
								height: 100%;
								object-fit: cover;
							}
						}
						
						.user-nickname {
							font-size: 28rpx;
							color: #333;
							margin-right: 10rpx;
							max-width: 120rpx;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}
						
						.post-time {
							font-size: 24rpx;
							color: #999;
						}
					}
					
					.post-tag {
						font-size: 24rpx;
						padding: 4rpx 16rpx;
						border-radius: 4rpx;
					}
				}
				
				.post-content {
					margin-bottom: 15rpx;
					
					.post-title {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 10rpx;
					}
					
					.post-text {
						font-size: 28rpx;
						color: #666;
						line-height: 1.5;
						margin-bottom: 15rpx;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 3;
						overflow: hidden;
					}
					
					.post-images {
						display: flex;
						flex-wrap: wrap;
						
						.post-image {
							width: 220rpx;
							height: 220rpx;
							margin-right: 10rpx;
							margin-bottom: 10rpx;
							border-radius: 8rpx;
							background-color: #f5f5f5;
						}
					}
				}
				
				.post-footer {
					display: flex;
					border-top: 1px solid #f5f5f5;
					padding-top: 15rpx;
					
					.action-item {
						margin-right: 40rpx;
						display: flex;
						align-items: center;
						font-size: 24rpx;
						color: #999;
						
						.icon-like-filled {
							color: #f56c6c;
						}
						
						.count {
							margin-left: 5rpx;
						}
					}
				}
			}
		}
		
		.load-more {
			text-align: center;
			padding: 20rpx 0;
			color: #999;
			font-size: 26rpx;
		}
		
		.float-btn {
			position: fixed;
			right: 30rpx;
			bottom: 100rpx;
			width: 100rpx;
			height: 100rpx;
			background: linear-gradient(135deg, #8cc9a1 0%, #6eb888 100%);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #fff;
			font-size: 40rpx;
			box-shadow: 0 4rpx 20rpx rgba(110, 184, 136, 0.4);
			z-index: 100;
		}
	}
</style> 